<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<u-navbar :safeAreaInsetTop="true">
			<template #left>
				<view class="u-nav-slot">
					<image src="/static/index/level.png" class="leave" @click="leaveFun"></image>
				</view>
			</template>
		</u-navbar>
		<!-- 顶部标签栏 -->
		<view class="tabs">
			<view v-for="tab in tabs" :key="tab.value" :class="['tab-item', activeTab === tab.value ? 'active' : '']"
				@click="switchTab(tab.value,tab.label)">
				{{ tab.label }}
				<view 
					v-if="getTabBadgeCount(tab.value) > 0" 
					class="tab-badge"
				>
					{{ getTabBadgeText(tab.value) }}
				</view>
			</view>
		</view>
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 左侧列表区域 -->
			<view class="list-section">
				<!-- 🆕 修改：启用下拉刷新 -->
				<scroll-view class="task-list" scroll-y 
					:refresher-enabled="true" 
					:refresher-triggered="refresherTriggered"
					@refresherrefresh="onRefresherRefresh"
					@scrolltolower="onScrollToLower" 
					:style="{ height: scrollViewHeight + 'px' }" 
					lower-threshold="50" 
					:show-scrollbar="false">
					
					<!-- 🆕 下拉刷新指示器 -->
				<!-- 	<view class="refresher-container" v-if="refresherTriggered">
						<text class="refresher-text">下拉刷新中...</text>
					</view> -->
					
					<view v-for="(task,index) in orderList" :key="task.erpNo+task.id"
						:class="['task-item', selectedTask?.id === task.id ? 'selected' : '']" @click.stop="selectTask(task)">
						
						<!-- 🆕 添加序号显示 -->
						<view class="index-badge">{{ index+1 }}</view>
						
						<view class="order-id">ERP单号：{{ task.erpNo }}</view>
						<view class="order-id">客户名称：{{ task.customerName }}</view>
						<!-- <view class="order-id">货物名称：{{ JSON.parse(task.goodsTable)[0].goodsName }}</view> -->
						<view class="order-id">客户地址：{{ task.customerAddress}}</view>
						<!-- <view class="order-id" style="word-break: break-word;">规格：{{ JSON.parse(task.goodsTable)[0].spec }}</view> -->
						<view class="order-id" style="word-break: break-word;">期望送达日期：{{task.expectArrivalTime?.replace('T', ' ')|| '暂无'}}</view>
						<view class="order-id">数量：{{ parseFloat(JSON.parse(task.goodsTable)[0].quantity) }}</view>
						<view class="order-id">卡：{{ task.cardboard }}</view>
						<view class="order-id">描述：{{ task.description }}</view>
						<view class="task-content">
							<view class="task-actions">
								<button v-if="activeTab === 'pending' " class="btn-primary">
									派送
								</button>
								<button v-else-if="activeTab === 'loading' && job=='107'" class="btn-primary">
									确认装车
								</button>
								<button v-else-if="activeTab === 'sending' && job=='107'" class="btn-primary">
									确认发货
								</button>
								<button v-else-if="activeTab === 'delivering' && job=='107'" class="btn-primary">
									确认送达
								</button>
								<button v-if="activeTab === 'reviewing' && job!='107'" class="btn-primary">
									审核
								</button>
							</view>
						</view>
					</view>

					<!-- 加载状态提示 -->
					<view class="loading-status">
						<text v-if="pagination.isLoading" class="loading-text">加载中...</text>
						<text v-else-if="!pagination.hasMore && orderList.length > 0" class="no-more-text">已加载全部数据</text>
						<text v-else-if="orderList.length === 0 && !pagination.isLoading" class="no-data-text">暂无数据</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch
	} from 'vue';
	import {
		logisticsApi
	} from '@/api/index.js'
	import {
		useUser
	} from '@/composables/useUser'

	const {
		job, 
		userId
	} = useUser()

	// 响应式数据
	const activeTab = ref('');
	const activeTabLabel = ref('');
	const selectedTask = ref(null);
	const scrollViewHeight = ref(0)
	const orderList = ref([]);
	// 🆕 下拉刷新状态
	const refresherTriggered = ref(false);

	// 在现有响应式数据后添加分页数据
	const pagination = ref({
		pageNum: 1, // 当前页码
		pageSize: 10, // 每页条数（根据实际情况调整）
		total: 0, // 总数据量
		hasMore: true, // 是否还有更多数据
		isLoading: false, // 是否正在加载
		isLoadMore: false // 是否加载更多
	});
	const form = ref({
		processStatus: ''
	});

	// 根据用户角色生成不同的标签配置[1,2](@ref)
	const tabs = computed(() => {
		const baseTabs = [
			// {
			// 	label: '待装车',
			// 	value: 'loading'
			// },
			{
				label: '待发货',
				value: 'sending'
			},
			{
				label: '待送达',
				value: 'delivering'
			},
			{
				label: '待审核',
				value: 'reviewing'
			},
			{
				label: '已完成',
				value: 'completed'
			}
		];

		// 调度员（非司机）显示待排班标签[5]
		if (job.value === '107') {
			return baseTabs;
		} else {
			// 司机角色不显示待排班
			return [{
					label: '待排班',
					value: 'pending'
				},
				...baseTabs
			];
		}
	});

	
	const tabBadgeCounts = ref({
	    pending: 0,    // 待排班数量
	    sending: 0,   // 待发货数量
	    delivering: 0,  // 待送达数量
	    reviewing: 0,  // 待审核数量
	    completed: 0    // 已完成数量
	});
	
	// 🆕 获取标签徽标数量
	const getTabBadgeCount = (tabValue) => {
	    return tabBadgeCounts.value[tabValue] || 0;
	};
	
	// 🆕 获取徽标显示文本（超过99显示99+）
	const getTabBadgeText = (tabValue) => {
	    const count = tabBadgeCounts.value[tabValue] || 0;
	    return count > 99 ? '99+' : count.toString();
	};

	const leaveFun = () => {
		uni.showModal({
			title: '退出确认',
			content: '您确定要退出登录吗？',
			confirmText: '确定',
			cancelText: '再想想',
			success: (res) => {
				if (res.confirm) {
					uni.clearStorageSync()
					uni.reLaunch({
						url: '/pages/login'
					})
				} else if (res.cancel) {
					console.log('用户点击了取消');
				}
			}
		});
	}
	
	// 监听tabs变化，确保默认选中第一个标签[7](@ref)
	watch(tabs, (newTabs) => {
		if (newTabs.length > 0 && !activeTab.value) {
			switchTab(newTabs[0].value, newTabs[0].label);
		}
	}, {
		immediate: true
	});

	const getOrderListFun = async (statuslabel, status) => {
		// 防止重复请求
		if (pagination.value.isLoading) return;

		// 如果是加载更多且没有更多数据，则直接返回
		if (pagination.value.isLoadMore && !pagination.value.hasMore) {
			return;
		}

		try {
			pagination.value.isLoading = true;

			
			// 如果不是加载更多，重置页码
			if (!pagination.value.isLoadMore) {
				pagination.value.pageNum = 1;
				pagination.value.hasMore = true;
				orderList.value = [];
			}
			
			if (status && statuslabel) {
				activeTab.value = status
				activeTabLabel.value = statuslabel
			}
			form.value.processStatus = activeTabLabel.value;
			let params={
				...form.value,
				pageNum: pagination.value.pageNum,
				pageSize: pagination.value.pageSize,
			}
			if(job.value=='107') params['transporterId']=userId.value
			const res = await logisticsApi.getOrderList(params);
				pagination.value.isLoading = false;
			if (res.data.rows && res.data.rows.length > 0) {
				if (pagination.value.isLoadMore) {
					// 加载更多：追加数据
					orderList.value = [...orderList.value, ...res.data.rows];
				} else {
					// 首次加载或切换标签：替换数据
					orderList.value = res.data.rows;
				}

				// 更新分页信息
				pagination.value.total = res.data.total;
				pagination.value.hasMore = orderList.value.length < res.data.total;
				if(form.value.processStatus=='待排班' && !pagination.value.isLoadMore)tabBadgeCounts.value.pending=res.data.total

				// 如果还有更多数据，页码+1
				if (pagination.value.hasMore) {
					pagination.value.pageNum++;
				}
			} else {
				// 没有数据
				pagination.value.hasMore = false;
				if (!pagination.value.isLoadMore) {
					orderList.value = [];
				}
			}
		} catch (error) {
			orderList.value = [];
			console.error('获取失败:', error);
		} finally {
			// 🆕 无论成功失败，都要关闭下拉刷新状态
			if (refresherTriggered.value) {
				setTimeout(() => {
					refresherTriggered.value = false;
				}, 500);
			}
		}
	}

	// 🆕 下拉刷新事件处理
	const onRefresherRefresh = async () => {
		console.log('下拉刷新触发');
		refresherTriggered.value = true;
		
		// 重置分页状态
		pagination.value.pageNum = 1;
		pagination.value.hasMore = true;
		pagination.value.isLoadMore = false;
		
		// 重新加载数据
		await getOrderListFun();
		
		// 显示刷新成功提示
		uni.showToast({
			title: '刷新成功',
			icon: 'success',
			duration: 1500
		});
	};

	// 切换标签方法
	const switchTab = (tabValue, tabLabel) => {
		pagination.value.isLoadMore=false
		activeTab.value = tabValue;
		activeTabLabel.value = tabLabel;
		selectedTask.value = null; // 切换标签时清空选中
		getOrderListFun();
	};

	const selectTask = (task) => {
		selectedTask.value = task;
		uni.navigateTo({
			url: `/pages/logistics/detail`,
			success: function(res) {
				res.eventChannel.emit('acceptTaskData', {
					task: task,
					timestamp: new Date().getTime()
				});
			}
		});
	};
	
	const getTotalData = async () => {
		let params={
			pageNum: pagination.value.pageNum,
			pageSize: pagination.value.pageSize,
		}
		if(job.value=='107') params['transporterId']=userId.value
		const res = await logisticsApi.getOrderList({...params,processStatus:'待发货'});
		const res2 = await logisticsApi.getOrderList({...params,processStatus:'待送达'});
		const res3 = await logisticsApi.getOrderList({...params,processStatus:'待审核'});
		
		tabBadgeCounts.value.sending=res.data.total
		tabBadgeCounts.value.delivering=res2.data.total
		tabBadgeCounts.value.reviewing=res3.data.total
		
	}

	// 滚动到底部触发的方法
	const onScrollToLower = () => {
		if (pagination.value.hasMore && !pagination.value.isLoading) {
			console.log('滚动到底部，加载更多数据...');
			pagination.value.isLoadMore=true
			getOrderListFun(); // true 表示是加载更多操作
		}
	};

	// 生命周期[8](@ref)
	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync();
		scrollViewHeight.value = systemInfo.windowHeight ;
		// 确保默认选中第一个可用的标签
		if (tabs.value.length > 0 && !activeTab.value) {
			switchTab(tabs.value[0].value, tabs.value[0].label);
			getTotalData()
		}
		// 监听刷新事件
		uni.$on('refreshOrderList', (data) => {
			getOrderListFun(data.status, data.loadingType);
			getTotalData()//更新total
		});
		
	});
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}
	/* 🆕 序号徽章样式 */
	.index-badge {
	    position: fixed;
	    right: 20rpx;
	    width: 60rpx;
	    height: 60rpx;
		text-align:right;
	    border-radius: 50%;
	    background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
	    color: white;
	    display: flex;
	    align-items: center;
	    justify-content: center;
	    font-size: 24rpx;
	    font-weight: bold;
	    box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
	    z-index: 1;
	}

	/* 标签栏样式 */
	.tabs {
		display: flex;
		background-color: #ffffff;
		border-bottom: 1px solid #e0e0e0;
		padding: 0 20rpx;
		justify-content: space-between;
		/* #ifdef H5 */
		margin-top: 90rpx;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		margin-top: 180rpx;
		/* #endif */
	}

	.tab-item {
		position: relative; 
		padding: 20rpx 22rpx; /* 右侧留出更多空间给徽标 */
		font-size: 28rpx;
		color: #666;
		border-bottom: 4rpx solid transparent;
		transition: all 0.3s;
	}
	
	.tab-badge {
	    position: absolute;
	    top: 8rpx;
	    right: -10rpx;
	    min-width: 40rpx;
	    height: 36rpx;
	    line-height: 36rpx;
	    border-radius: 18rpx;
	    background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
	    color: white;
	    font-size: 20rpx;
	    font-weight: bold;
	    text-align: center;
	    box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
	    z-index: 2;
	}
	
	.tab-item.active {
		color: #007AFF;
		border-bottom-color: #007AFF;
		font-weight: bold;
	}

	/* 主要内容区域 */
	.main-content {
		display: flex;
		flex: 1;
		padding: 20rpx;
	}

	/* 左右分区公共样式 */
	.list-section {
		display: flex;
		flex-direction: column;
	}

	/* 任务列表样式 */
	.task-list {
		/* padding: 0 20rpx; */
		width: 100%;
	}

	/* 🆕 下拉刷新容器样式 */
	.refresher-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
		background-color: #f8f9fa;
	}

	.refresher-text {
		font-size: 26rpx;
		color: #007AFF;
	}

	.task-item {
		box-sizing: border-box;
		flex: 0 0 auto;
		/* 不放大(flex-grow:0)、不缩小(flex-shrink:0)、基于内容尺寸(flex-basis:auto) */
		padding: 20rpx 30rpx;
		/* 您的padding值，现在会被包含在总宽度内 */
		font-size: 28rpx;
		color: #666;
		border-bottom: 4rpx solid transparent;
		transition: all 0.3s;
		/* white-space: nowrap; */
		margin-bottom: 15rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		background-color: #ffffff;
	}

	.task-item.selected {
		background-color: #f8f9ff;
		border-left: 4rpx solid #007AFF;
	}

	.task-item:last-child {
		border-bottom: none;
	}

	.order-id {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 10px;
	}

	.task-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 16rpx;
	}

	/* 按钮样式 */
	.task-actions button {
		padding: 4rpx 44rpx;
		font-size: 24rpx;
		border-radius: 16rpx;
		border: none;
		color: white;
	}

	.btn-primary {
		background-color: #007AFF;
	}

	.btn-secondary {
		background-color: #FF6B35;
	}

	.btn-success {
		background-color: #4CD964;
	}

	/* 无数据状态 */
	.no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
	}

	.no-data-text {
		font-size: 28rpx;
		color: #999;
	}

	.leave {
		width: 50rpx;
		height: 50rpx;
	}

	.loading-status {
		padding: 30rpx;
		text-align: center;
	}

	.loading-text {
		color: #007AFF;
		font-size: 26rpx;
	}

	.no-more-text {
		color: #999;
		font-size: 26rpx;
	}

	.no-data-text {
		color: #999;
		font-size: 28rpx;
	}

	/* 响应式设计 */
	@media (max-width: 768px) {
		.main-content {
			flex-direction: column;
		}

		.list-section {
			width: 100%;
		}
	}
</style>ss